<?php

use \Welcomescreen\Agavi\Model;
use \Welcomescreen\Exceptions;
use \Welcomescreen\Objects;

class TemplateManagerModel extends Model\BaseModel implements \AgaviISingletonModel {
	/**
	 * @var array(string => Welcomescreen\Objects\Template)
	 */
	protected $templates;
	
	/**
	 * Loads all templates from the template store
	 */
	protected function loadTemplates() {
		if($this->templates !== null) {
			return;
		}
		
		$this->templates = array();
		$templateData = require(AgaviConfigCache::checkConfig(AgaviConfig::get('org.welcomescreen.system.config_dir') . '/templates.xml'));
		foreach($templateData['templates'] as $templateName => $data) {
			$variableData = isset($data['variables']) ? $data['variables'] : array();
			$variables = array();
			foreach($variableData as $name => $variable) {
				$optional = isset($variable['optional']) ? $variable['optional'] : false;
				if(is_numeric($optional)) {
					$optional = (bool) $optional;
				} elseif(is_string($optional)) {
					$optional = ($optional == 'true');
				}
				$variables[$name] = new Objects\TemplateVariable($name, $variable['field'], $variable['type'], $optional);
			}
			$directory = isset($data['directory']) ? $data['directory'] : null;
			$this->templates[$templateName] = new Objects\Template($templateName, $data['file'], $directory, $variables);
		}
	}
	
	/**
	 * Checks if a template with the given name exists.
	 *
	 * @param string $name 
	 * @return bool
	 */
	public function hasTemplate($name) {
		$this->loadTemplates();
		return isset($this->templates[$name]);
	}
	
	/**
	 * Retrieves a template (by name). If the template doesn't exist NonexistentObjectException is thrown.
	 * 
	 * @param string $name
	 * @return Welcomescreen\Objects\Template
	 */
	public function getTemplate($name) {
		$this->loadTemplates();
		if(isset($this->templates[$name])) {
			return $this->templates[$name];
		}
		
		throw new Exceptions\NonexistentObjectException('The template with the name "' . $name . '" does not exist');
	}
	
	/**
	 * Retrieves all templates.
	 * 
	 * @return array(string => Welcomescreen\Objects\Template)
	 */
	public function getTemplates() {
		$this->loadTemplates();
		return $this->templates;
	}
}

?>